package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.util.AESUtil;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.JiQiongBaoParam;
import com.block.source.model.api.JiaHuiTongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class JiaHuiTongReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret();


        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"撞库传入的信息为空",null,null));
            return sourceApiResult;
        }

        String data = jsonObjectParamContent.getString("data");

        String  paramContentData = decryptAES(data,apiSecretSubstring);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("requestId")) ||   StrUtil.isEmpty(jsonObject.getString("phone"))
            || jsonObject.getInteger("gender") == null || StrUtil.isEmpty(jsonObject.getString("city")) || jsonObject.getInteger("sesamePoints") == null ||
            jsonObject.getInteger("loanLimit") == null || jsonObject.getInteger("car") == null || jsonObject.getInteger("house") == null || jsonObject.getInteger("accumulationFund") == null )
        {
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"城市信息为空",null,null));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret();


        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"进件传入的信息为空",null,null));
            return sourceApiResult;
        }

        String data = jsonObjectParamContent.getString("data");

        String paramContentData = decryptAES(data, apiSecretSubstring);
        JiaHuiTongParam jiaHuiTongParam = JSON.parseObject(paramContentData, JiaHuiTongParam.class);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(jiaHuiTongParam.getPhone());
        userDataParam.setRealName(jiaHuiTongParam.getName());

        String reqNo = jiaHuiTongParam.getRequestId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), reqNo);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("msg", "请求成功");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logoUrl", "");
            }else {
                dataObject.put("logoUrl", companyLogo);
            }
            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("longLimit", "24");
            dataObject.put("maxLimit", "200000");
            dataObject.put("minRate", "2.4");
            dataObject.put("price", Float.valueOf(String.valueOf(pushResultInfo.getPriceAmount())));

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title",protocolInfo.getProtocolName());
                jsonObject.put("protocol", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("longLimit", "24");
            dataObject.put("maxLimit", "200000");
            dataObject.put("minRate", "2.4");
            dataObject.put("price", Float.valueOf(String.valueOf(pushResultInfo.getPriceAmount())));
            //协议地址
            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("title","授权协议");
            jsonObject.put("protocol", protocolUrl);
            jsonArray.add(jsonObject);
        }

        JSONObject data = resultInfoVO.getData();
        JSONArray md5List = data.getJSONArray("md5List");
        String md5String = md5List != null ? md5List.toString() : "";
        dataObject.put("md5list", md5String);

        dataObject.put("protocolList", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        String respCode = resultInfoVO.getRespCode();
        JSONObject data = resultInfoVO.getData();
        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("进件失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 1);
        returnObject.put("msg", message);
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("msg", "进件成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        JiaHuiTongParam jiaHuiTongParam = JSON.parseObject(paramContent, JiaHuiTongParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(jiaHuiTongParam.getRequestId());

        userDataParam.setMobileMask(jiaHuiTongParam.getPhone().substring(0,8));

        if(jiaHuiTongParam.getName() != null){
            userDataParam.setRealName(jiaHuiTongParam.getName());
        }

        userDataParam.setSex(String.valueOf(jiaHuiTongParam.getGender()));
        if(jiaHuiTongParam.getIdCard() != null){
            userDataParam.setIdCard(jiaHuiTongParam.getIdCard());
        }

        userDataParam.setAge(jiaHuiTongParam.getAge());
        String city = jiaHuiTongParam.getCity();

        if (city.endsWith("市") || city.endsWith("洲") || city.endsWith("区") || city.endsWith("盟")) {
            AddressInfo addresInfoByCity = addressInfoService.getAddresInfoByCity(city);
            userDataParam.setCityCode(addresInfoByCity.getCityCode());
        } else {
            String cityWithSuffix = city + "市";
            AddressInfo addresInfoByCity = addressInfoService.getAddresInfoByCity(cityWithSuffix);
            userDataParam.setCityCode(addresInfoByCity.getCityCode());
        }


        Integer sesamePoints = jiaHuiTongParam.getSesamePoints();
        if(sesamePoints == 0){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }else if(sesamePoints == 1 ||  sesamePoints == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else if(sesamePoints == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if(sesamePoints == 4){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if(sesamePoints == 5){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }

        Integer loanLimit = jiaHuiTongParam.getLoanLimit();
        if(loanLimit == 0 ||   loanLimit == 1){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else if(loanLimit == 2){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        }else if(loanLimit == 3){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        }else if(loanLimit == 4){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        }else if(loanLimit == 5 ||  loanLimit == 6){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer car = jiaHuiTongParam.getCar();
        if(car == 0){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }

        Integer house = jiaHuiTongParam.getHouse();
        if(house == 0){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu002.getValue());
        }

        Integer accumulationFund = jiaHuiTongParam.getAccumulationFund();
        if(accumulationFund == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }

        Integer socialSecurity = jiaHuiTongParam.getSocialSecurity();
        if(socialSecurity == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }

        Integer insurance = jiaHuiTongParam.getInsurance();
        if(insurance == null){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else if(insurance == 0){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());
        }

        Integer flowers = jiaHuiTongParam.getFlowers();
        if(flowers == null){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb002.getValue());
        }

        Integer whiteStripe = jiaHuiTongParam.getWhiteStripe();
        if(whiteStripe == null){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }else {
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());
        }

        Integer creditStatus = jiaHuiTongParam.getCreditStatus();
        if(creditStatus == null){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else if(creditStatus == 0){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else if(creditStatus == 1){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt001.getValue());

        Integer company = jiaHuiTongParam.getCompany();
        if(company == 0){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }else if(company == 1){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if(company == 2){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else if(company == 3){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if(company == 4){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }

        Integer educationLevel = jiaHuiTongParam.getEducationLevel();
        if(educationLevel == null){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }else if(educationLevel == 0 ||  educationLevel == 1 || educationLevel == 9) {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }else if(educationLevel == 2 || educationLevel == 3){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl002.getValue());
        }else if(educationLevel == 4){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl003.getValue());
        }else if(educationLevel == 5){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
        }else if(educationLevel == 6 ||  educationLevel == 7 ||   educationLevel == 8){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl005.getValue());
        }

        Integer creditCard = jiaHuiTongParam.getCreditCard();
        if(creditCard == null){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr003.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        userDataParam.setUserIp("127.0.0.1");

        return userDataParam;
    }


    public static String decryptAES(String data, String key) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
            return new String(decrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public JSONObject getCheckAndRegister(Integer code,String message,Integer status,String orderNo) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",code);
        returnObject.put("msg", message);
        JSONObject dataJson = new JSONObject();
        if (code == 200){
            dataJson.put("status",status);
            dataJson.put("orderNo",orderNo);
        }
        returnObject.put("data",dataJson);
        return returnObject;
    }

    public JSONObject getCheckSuccess(Integer code,String message,Integer status,String orderNo,SourceApiParam sourceApiParam,SourceBaseInfo sourceBaseInfo) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",code);
        returnObject.put("msg", message);
        JSONObject dataJson = new JSONObject();
        if (code == 200){
            dataJson.put("status",status);
            dataJson.put("orderNo",orderNo);
            MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
            SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
            dataJson.put("productName", merchantBaseInfo.getInfoName());
            dataJson.put("companyName", merchantBaseInfo.getCompanyName());
            //协议地址
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("contractName","授权协议");
            jsonObject.put("contractUrl", protocolUrl);
            jsonArray.add(jsonObject);
            dataJson.put("contractList", jsonArray);
        }
        returnObject.put("data",dataJson);
        return returnObject;
    }






}
